package org.example.aienglishapp.service.article;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BaiduFanyiService {

    private static final Logger logger = LoggerFactory.getLogger(ArticleService.class);


    @Value("${baidu.fanyi.appId}")
    private String appId;

    @Value("${baidu.fanyi.secretKey}")
    private String secretKey;

    public String translate(String text, String from, String to) {
        if (text == null || text.trim().isEmpty()) {
            throw new IllegalArgumentException("待翻译的文本不能为空");
        }

        try {
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/x-www-form-urlencoded");

            // 构建请求体
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("q", text);
            body.add("from", from);
            body.add("to", to);
            body.add("appid", appId);
            String salt = String.valueOf(generateSalt());
            body.add("salt", salt);
            body.add("sign", generateSign(text, salt));

            // 发送请求
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    "http://api.fanyi.baidu.com/api/trans/vip/translate",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            // 解析返回的 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response.getBody());

            // 检查 API 响应中的错误码
            if (rootNode.has("error_code") && rootNode.get("error_code").asText() != null) {
                String errorCode = rootNode.get("error_code").asText();
                String errorMsg = rootNode.has("error_msg") ? rootNode.get("error_msg").asText() : "未知错误";
                throw new RuntimeException("百度翻译API错误: " + errorCode + " - " + errorMsg);
            }


            // 获取翻译结果并去除HTML标签
            JsonNode transResultNode = rootNode.path("trans_result");
            if (transResultNode.isArray() && transResultNode.size() > 0) {
                String translatedText = transResultNode.get(0).path("dst").asText();
                // 去除HTML标签
                return removeHtmlTags(translatedText);
            } else {
                throw new RuntimeException("Translation result not found in API response");
            }

        }  catch (Exception e) {
            // 可以进一步记录日志或处理特定异常类型
            logger.error("翻译过程中发生异常: {}", e.getMessage());
            throw new RuntimeException("翻译失败: " + e.getMessage(), e); // 抛出异常而不是返回字符串
        }
    }
    private String removeHtmlTags(String text) {
        // 使用正则表达式去除所有HTML标签
        if (text != null) {
            Pattern pattern = Pattern.compile("<[^>]*>");
            Matcher matcher = pattern.matcher(text);
            return matcher.replaceAll("");  // 替换所有HTML标签为空字符串
        }
        return text;
    }

    private String generateSign(String text, String salt) {
        String signStr = appId +  text + salt + secretKey;
        System.out.println("Sign string: " + signStr);//打印签名字符串
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(signStr.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("生成签名时发生错误: " + e.getMessage(), e);
        }
    }

    private int generateSalt() {
        // 使用 SecureRandom 生成一个更为安全的随机数
        SecureRandom random = new SecureRandom();
        return random.nextInt(Integer.MAX_VALUE);
    }
}